from django.contrib.auth.backends import ModelBackend
from .models import User
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadData
from django.conf import settings
import re


def get_user_by_account(account):
    try:
        # 避免用户名格式和手机号一样，必须先判断手机号
        if re.match(r'1[3-9]\d{9}', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileModelBackend(ModelBackend):
    """自定义手机认证类"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        # try:
        #     # 避免用户名格式和手机号一样，必须先判断手机号
        #     if re.match(r'1[3-9]\d{9}',username):
        #         user = User.objects.get(mobile=username)
        #     else:
        #         user = User.objects.get(username=username)
        # except User.DoesNotExist:
        #     return None
        # else:
        #     return user
        user = get_user_by_account(username)
        if user and user.check_password(password):
            return user


def generate_email_url(user):
    """加密邮箱认证url"""
    serializer = Serializer(settings.SECRET_KEY,3600*24)
    data = {'user_id':user.id,'email':user.email}
    token = serializer.dumps(data).decode()
    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token
    return verify_url


def check_email_url(token):
    """解密邮箱认证url"""
    serializer = Serializer(settings.SECRET_KEY, 3600 * 24)
    try:
        data = serializer.loads(token)
        user_id = data.get('user_id')
        email = data.get('email')

        try:
            user = User.objects.get(id=user_id, email=email)
            return user
        except User.DoesNotExist:
            return None

    except BadData:
        return None






